package com.haohan.cloud.scm.common.tools.util;


import cn.hutool.json.JSONUtil;
import com.haohan.cloud.framework.entity.BaseResp;
import com.haohan.cloud.scm.common.tools.http.HttpClientHelper;
import com.haohan.cloud.scm.common.tools.http.MethodType;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by zgw on 2019/5/22.
 */
@Component
public class ApiCallUtil {

  @Autowired
  private HttpClientHelper httpClientHelper;


  public String getCall(String url, Object reqBean) {
    return apiCall(MethodType.GET, url, reqBean, null);
  }

  public String postCall(String url, Object reqBean) {
    return apiCall(MethodType.POST, url, reqBean, null);
  }


  public <Resp> Resp apiCallResp(MethodType type, String url, Object reqClass, Class<Resp> respClass, HashMap<String, Object> header) {

    String result = apiCall(type, url, reqClass, header);
    if (StringUtils.isNotEmpty(result)) {
      return JSONUtil.toBean(result, respClass);
    }
    return null;
  }

  public BaseResp apiInvoke(MethodType type, String url, Object reqClass) {

    return apiCallResp(type, url, reqClass, BaseResp.class, null);

  }

    public BaseResp apiInvoke(MethodType type, String url, Object reqClass, HashMap<String, Object> header) {

        return apiCallResp(type, url, reqClass, BaseResp.class, header);

    }


//  public static void main(String[] args) {
//    BaseResp resp = BaseResp.newSuccess();
//
//    resp.setExt(new Person("jack", "12"));
//
//    String json = resp.toJson();
//    System.out.println(json);
//
//    BaseResp respN = JSONUtil.toBean(json, BaseResp.class);
//
//    Person person = JSONUtil.toBean(respN.getExt().toString(), Person.class);
//
//    System.out.println(person.getName());
  //  @Data
//  @AllArgsConstructor
//  private static class Person implements Serializable {
//
//    private String name;
//    private String age;
//  }
//
//  }


  public String apiCall(MethodType type, String url, Object reqClass, HashMap<String, Object> header) {

    Map<String, Object> reqParams = null;

    try {
      reqParams = cn.hutool.core.bean.BeanUtil.beanToMap(reqClass, false, true);
    } catch (Exception e) {
      e.printStackTrace();
    }

    if (null == reqParams) {
      return null;
    }

    return httpClientHelper.call(type, url, reqParams, header);

  }


}
